package com.leetcode;

import com.leetcode.common.ListNode;

/**
 * 19. 删除链表的倒数第 N 个结点
 * 计算链表长度, 然后移动到待删除节点的前一个节点, 然后删除待删除节点
 *
 * @author fy
 * @date 2022/4/11 15:58
 */
public class Solution19 {

    public ListNode removeNthFromEnd(ListNode head, int n) {
        if (head == null) {
            return null;
        }
        ListNode dummyHead = new ListNode(-1, head);
        ListNode cur = dummyHead.next;
        int length = 0;
        while (cur != null) {
            length++;
            cur = cur.next;
        }
        if (n > length) {
            throw new RuntimeException("n is big than link list length");
        }
        cur = dummyHead;
        for (int i = 0; i < length - n; i++) {
            if (cur == null) {
                throw new RuntimeException("node is null");
            }
            cur = cur.next;
        }
        cur.next = cur.next.next;
        return dummyHead.next;
    }

}
